import { Typography } from "antd";
import { FC } from "react";
import { nanoid } from "nanoid";
import {
  componentConfGroup,
  ComponentConfType,
} from "@/components/QuestionComponents";
import styles from "./ComponentLib.module.scss";
import { useDispatch } from "react-redux";
import { addComponent } from "@/store/componentsReducer";

const { Title } = Typography;

const ComponentLib: FC = () => {
  const dispatch = useDispatch();

  function genComponent(c: ComponentConfType) {
    const { Component, type, title, defaultProps } = c;

    const handleComponentClick = () => {
      dispatch(
        addComponent({
          fe_id: nanoid(),
          type,
          title,
          props: defaultProps,
        })
      );
    };

    return (
      <div className={styles.wrapper} key={type} onClick={handleComponentClick}>
        <div className={styles.component}>
          <Component />
        </div>
      </div>
    );
  }

  return (
    <div>
      {componentConfGroup.map(({ groupId, groupName, components }, index) => (
        <div key={groupId}>
          <Title level={5} style={{ marginTop: index > 0 ? "20px" : "0" }}>
            {groupName}
          </Title>
          <div>{components.map((c) => genComponent(c))}</div>
        </div>
      ))}
    </div>
  );
};

export default ComponentLib;
